package com.sky.task;

import com.sky.entity.OrderEntity;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单相关定时任务
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    @Scheduled(cron = "0 0/1 * * * ?") // 每分钟执行一次
    public void processTimeoutOrder() {
        log.info("处理超时订单");
        // 调用select查询状态为待付款，并且时间超出了15分钟
        List<OrderEntity> orders = orderMapper.getOrderByStatusAndOrderTimeWith15MinuteAgo(OrderEntity.TO_BE_PAID);
        log.info("超时订单包括 =>{}", orders);
        if (orders.size() > 0) {
            orderMapper.updateBatchByStatus(OrderEntity.CANCELLED, orders.stream().map(OrderEntity::getId).collect(Collectors.toList()));
        }
    }

    @Scheduled(cron = "0 0 1 * * ?") // 每日凌晨1点执行一次
    public void processNotSendOrder() {
        log.info("处理未派送完的订单");
        LocalDateTime localDateTime = LocalDateTime.now().minusHours(1); // 减去小时
        List<OrderEntity> orderByStatusAndOrderTimeLT = orderMapper.getOrderByStatusAndOrderTimeLT(OrderEntity.DELIVERED, localDateTime);
        log.info("未派送完的订单包括 =>{}", orderByStatusAndOrderTimeLT);
        if (orderByStatusAndOrderTimeLT.size() > 0) {
            orderMapper.updateBatchByStatus(OrderEntity.CANCELLED, orderByStatusAndOrderTimeLT.stream().map(OrderEntity::getId).collect(Collectors.toList()));
        }
    }
}
